/*
 * JBeagle - a Java toolkit for genetic algorithms.
 * 
 * Copyright (c) 2010 Matthijs Snel
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package jbeagle.core.select;

import java.util.Arrays;

import jbeagle.core.Individual;
import jbeagle.core.Population;


public class TournamentSelector implements Selector {
	
	public static final double DEFAULT_RATE = 0.75;
	
	private double rate;
	private int size;
	
	public TournamentSelector( int tournamentSize ) {
		this(tournamentSize, DEFAULT_RATE);
	}
	
	public TournamentSelector( int tournamentSize, double rate ) {
		setSize(tournamentSize);
		setRate(rate);
	}
	
	public <I extends Individual<G>, G> Population<I, G> apply( Population<I, G> pop ) {
		Population<I, G> nextPop = new Population<I, G>( pop.size() );
		Individual[] tournament = new Individual[size];
		int j;
		
		while ( nextPop.size() < pop.size() ) {
			for ( int i = 0; i < size; i++ ) {
				j = (int) Math.round(Math.random() * (pop.size()-1));
				tournament[i] = pop.get(j);
			}
			passToNextPop( tournament, nextPop );
		}
		return nextPop;		
	}
	
	public void setRate( double rate ) {
		this.rate = rate;
	}
	
	public double getRate() {
		return rate;
	}
	
	public void setSize( int tournamentSize ) {
		size = tournamentSize;
	}
	
	public int getSize() {
		return size;
	}
	
	protected void passToNextPop( Individual[] tournament, Population next ) {
		Arrays.sort(tournament);
		int pos = size-1;
		double r = Math.random();

		while( r > rate && pos > 0 ) {
			pos--;
			r = Math.random();
		}

		next.add( tournament[pos].copy() );
	}
}
